package cn.chiship.framework.upms.biz.user.controller;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.user.entity.UpmsPermission;
import cn.chiship.framework.upms.biz.user.entity.UpmsPermissionExample;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsFastCreatePermissionDto;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsMenuDto;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsPermissionDto;
import cn.chiship.framework.upms.biz.user.pojo.vo.UpmsPermissionVo;
import cn.chiship.framework.upms.biz.user.service.UpmsPermissionService;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.sdk.framework.util.FrameworkUtil;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限控制层
 * 2021/9/27
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/permission")
@Api(tags = "权限管理")
public class UpmsPermissionController extends BaseController<UpmsPermission, UpmsPermissionExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsPermissionController.class);

    @Resource
    private UpmsPermissionService upmsPermissionService;

    @Override
    public BaseService getService() {
        return upmsPermissionService;
    }

    @ApiOperation(value = "菜单树形表格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "menuName", value = "菜单名称", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/menuTreeTable")
    public ResponseEntity<BaseResult> menuTreeTable(
            @RequestParam(required = false, defaultValue = "-gmtModified", value = "sort") String sort,
            @RequestParam(required = false, defaultValue = "", value = "menuName") String menuName) {
        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        /**
         * 创造条件
         */
        UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO).andTypeEqualTo(Byte.valueOf("1"));
        if (!StringUtil.isNullOrEmpty(menuName)) {
            criteria.andNameLike("%" + menuName + "%");
        }
        upmsPermissionExample.setOrderByClause(FrameworkUtil.formatSort(sort));
        List<UpmsPermission> upmsPermissions = upmsPermissionService.selectByExample(upmsPermissionExample);
        List<UpmsPermissionVo> permissions = assemblyPermission("0", upmsPermissions);
        return super.responseEntity(BaseResult.ok(permissions));
    }

    @ApiOperation(value = "权限树形表格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", required = false, dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "menuName", value = "菜单名称", defaultValue = "", required = false, dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/permissionTreeTable")
    public ResponseEntity<BaseResult> permissionTreeTable(
            @RequestParam(required = false, defaultValue = "-gmtModified", value = "sort") String sort,
            @RequestParam(required = false, defaultValue = "", value = "menuName") String menuName) {
        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        /**
         * 创造条件
         */
        UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(menuName)) {
            criteria.andNameLike("%" + menuName + "%");
        }
        upmsPermissionExample.setOrderByClause(FrameworkUtil.formatSort(sort));
        List<UpmsPermission> upmsPermissions = upmsPermissionService.selectByExample(upmsPermissionExample);
        List<UpmsPermissionVo> permissions = assemblyPermission("0", upmsPermissions);
        return super.responseEntity(BaseResult.ok(permissions));
    }

    @ApiOperation(value = "根据菜单获取权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid", value = "父级菜单", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/listPermission")
    public ResponseEntity<BaseResult> listPermission(@RequestParam(defaultValue = "", value = "pid") String pid) {
        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        /**
         * 创造条件
         */
        UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO).andPidEqualTo(pid).andTypeEqualTo(Byte.valueOf("2"));
        /**
         * 排序
         */
        upmsPermissionExample.setOrderByClause(FrameworkUtil.formatSort("+orders"));
        return super.responseEntity(BaseResult.ok(upmsPermissionService.selectByExample(upmsPermissionExample)));
    }

    @SystemOptionAnnotation(describe = "保存权限", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "保存权限")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsPermissionDto upmsPermissionDto) {
        UpmsPermission upmsPermission = new UpmsPermission();
        BeanUtils.copyProperties(upmsPermissionDto, upmsPermission);
        upmsPermission.setType(Byte.valueOf("2"));
        return super.responseEntity(super.save(upmsPermission));

    }

    @SystemOptionAnnotation(describe = "快速创建权限", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "快速创建权限")
    @PostMapping(value = "fastCreatePermission")
    public ResponseEntity<BaseResult> fastCreatePermission(@RequestBody @Valid UpmsFastCreatePermissionDto upmsFastCreatePermissionDto) {
        UpmsPermission upmsPermission = upmsPermissionService.selectByPrimaryKey(upmsFastCreatePermissionDto.getPid());
        if (StringUtil.isNull(upmsPermission)) {
            return super.responseEntity(BaseResult.error("所属菜单不存在"));
        }
        upmsPermission.setId(SnowflakeIdUtil.generateStrId());
        upmsPermission.setType(Byte.valueOf("2"));
        upmsPermission.setPermissionValue(upmsPermission.getPermissionValue() + ":" + upmsFastCreatePermissionDto.getPermissionValue());
        upmsPermission.setPid(upmsFastCreatePermissionDto.getPid());
        upmsPermission.setIcon(null);
        switch (upmsFastCreatePermissionDto.getPermissionValue()) {
            case "save":
                upmsPermission.setName("新增" + upmsPermission.getName());
                upmsPermission.setOrders(1L);
                break;
            case "update":
                upmsPermission.setName("编辑" + upmsPermission.getName());
                upmsPermission.setOrders(2L);
                break;
            case "details":
                upmsPermission.setName("详情" + upmsPermission.getName());
                upmsPermission.setOrders(3L);
                break;
            case "remove":
                upmsPermission.setName("删除" + upmsPermission.getName());
                upmsPermission.setOrders(4L);
                break;
            case "removeAll":
                upmsPermission.setName("批量删除" + upmsPermission.getName());
                upmsPermission.setOrders(5L);
                break;
            case "import":
                upmsPermission.setName("导入" + upmsPermission.getName());
                upmsPermission.setOrders(6L);
                break;
            case "export":
                upmsPermission.setName("导出" + upmsPermission.getName());
                upmsPermission.setOrders(7L);
                break;
            default:
                return super.responseEntity(BaseResult.error("不能识别的菜单权限【" + upmsFastCreatePermissionDto.getPermissionValue() + "】"));
        }
        return super.responseEntity(upmsPermissionService.insertSelective(upmsPermission));

    }

    @SystemOptionAnnotation(describe = "更新权限", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限id", required = true, dataTypeClass = String.class, paramType = "query"),
    })
    @ApiOperation(value = "更新权限")
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsPermissionDto upmsPermissionDto) {
        UpmsPermission upmsPermission = new UpmsPermission();
        BeanUtils.copyProperties(upmsPermissionDto, upmsPermission);
        upmsPermission.setType(Byte.parseByte("2"));
        return super.responseEntity(super.update(id, upmsPermission));
    }

    @SystemOptionAnnotation(describe = "保存菜单", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "保存菜单")
    @PostMapping(value = "menuSave")
    public ResponseEntity<BaseResult> menuSave(@RequestBody @Valid UpmsMenuDto upmsMenuDto) {

        UpmsPermission upmsPermission = new UpmsPermission();
        BeanUtils.copyProperties(upmsMenuDto, upmsPermission);
        upmsPermission.setPermissionValue(upmsMenuDto.getMenuCode());
        upmsPermission.setType(Byte.valueOf("1"));
        return super.responseEntity(super.save(upmsPermission));
    }

    @SystemOptionAnnotation(describe = "更新菜单", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单id", required = true, dataTypeClass = String.class, paramType = "query"),
    })
    @ApiOperation(value = "更新菜单")
    @PostMapping(value = "menuUpdate/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsMenuDto upmsMenuDto) {
        UpmsPermission upmsPermission = new UpmsPermission();
        BeanUtils.copyProperties(upmsMenuDto, upmsPermission);
        upmsPermission.setPermissionValue(upmsMenuDto.getMenuCode());
        upmsPermission.setType(Byte.valueOf("1"));
        return super.responseEntity(super.update(id, upmsPermission));
    }

    @SystemOptionAnnotation(describe = "删除权限和菜单", option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE)
    @ApiOperation(value = "删除权限&菜单")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {

        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        upmsPermissionExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(upmsPermissionExample));
    }

    @SystemOptionAnnotation(describe = "菜单和权限启用和锁定", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiOperation(value = "菜单&权限启用&锁定")
    @PostMapping(value = "changeIsState/{id}")
    public ResponseEntity<BaseResult> changeIsState(@PathVariable("id") String id, @RequestBody @Valid Boolean isDisabled) {
        return super.responseEntity(upmsPermissionService.changeIsState(id, isDisabled));
    }

    @SystemOptionAnnotation(describe = "下载权限编码", option = BusinessTypeEnum.SYSTEM_OPTION_OTHER)
    @ApiOperation(value = "下载权限编码")
    @PostMapping(value = "downloadPermissionCode")
    public void downloadPermissionCode(HttpServletResponse response) {
        upmsPermissionService.downloadPermissionCode(response);
    }

    public List<UpmsPermissionVo> assemblyPermission(String pid, List<UpmsPermission> menus) {
        List<UpmsPermissionVo> permissionVos = new ArrayList<>();
        for (UpmsPermission permission : menus) {
            if (!StringUtil.isNullOrEmpty(permission.getPid()) && permission.getPid().equals(pid)) {
                UpmsPermissionVo permissionVo = new UpmsPermissionVo();
                BeanUtils.copyProperties(permission, permissionVo);
                permissionVos.add(permissionVo);
            }

        }
        for (UpmsPermissionVo permissionVo : permissionVos) {
            permissionVo.setPermissionVos(assemblyPermission(permissionVo.getId(), menus));
        }
        return permissionVos;
    }
}
